<?php

namespace app\teacher\controller;

use app\common\controller\Frontend;
use app\common\model\banxi\Grade;
use think\exception\ValidateException;
use think\facade\Validate;

class User extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取用户信息
     * @return void
     */
    public function userInfo()
    {
        $userInfo = $this->auth->getUserInfo();
        $this->ok(__('Operation completed'), $userInfo);
    }

    public function updateInfo()
    {
        $param = $this->request->param([
            'avatar' => '',
            'name' => '',
            'gradeId' => '',
            'sex' => '',
        ]);
        try {
            $validate = Validate::rule([
                'gradeId' => function ($value) {
                    if (!$value) {
                        return true;
                    }
                    $gradeInfo = Grade::where('id', $value)->find();
                    if (!$gradeInfo) {
                        return '年级不存在';
                    }
                    return true;
                },
                'sex' => function ($value) {
                    if (!$value) {
                        return true;
                    }
                    if (!in_array($value, [1, 2])) {
                        return '请设置正确的性别';
                    }
                    return true;

                },
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $user = $this->auth->getUser();
        if ($param['avatar']) {
            $user->avatar = $param['avatar'];
        }
        if ($param['name']) {
            $user->name = $param['name'];
        }
        if ($param['gradeId']) {
            $user->gradeId = $param['gradeId'];
        }
        if ($param['sex']) {
            $user->sex = $param['sex'];
        }
        $user->save();
        $this->ok(__('Operation completed'));
    }


}